// ------------------------------------------------------------------------------------------
// Licensed by Interprise Solutions.
// http://www.InterpriseSolutions.com
// For details on this license please visit  the product homepage at the URL above.
// THE ABOVE NOTICE MUST REMAIN INTACT.
// ------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.SessionState;
using System.IO;

namespace InterpriseSuiteEcommerceCommon.InterpriseIntegration.Web
{
    public class DownloadHandler : IHttpHandler, IRequiresSessionState
    {
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            // first let's make sure the request came from the download page : download.aspx
            if (null == context.Request.UrlReferrer ||
                !Path.GetFileName(context.Request.UrlReferrer.LocalPath).ToLower().Equals("download.aspx"))
            {
                HttpResponseHelper.RespondWithFileNotFound(context.Response);
                return;
            }

            string downloadId = CommonLogic.QueryStringCanBeDangerousContent("d");
            if (string.IsNullOrEmpty(downloadId))
            {
                HttpResponseHelper.RespondWithFileNotFound(context.Response);
            }

            // check if the file exists
            DownloadableItem download = DownloadableItem.FindByDownloadId(downloadId);

            InterpriseSuiteEcommercePrincipal principal = HttpContext.Current.User as InterpriseSuiteEcommercePrincipal;
            if (null == principal || null == principal.ThisCustomer)
            {
                // customer must be logged in
                HttpResponseHelper.RespondWithFileNotFound(context.Response);
            }

            DownloadManager.DownloadFile(context, principal.ThisCustomer, download);
        }
    }
}
